package hikvision

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/SyncMap"
	"github.com/icholy/digest"
	"net/http"
	"strings"
	"sync"
	"time"
)

type clientManager struct {
	clients sync.Map
}

func (e *clientManager) Register(ip, username, password string) {
	host := "http://" + strings.ToLower(ip)

	options := make(map[string]interface{})
	options["host"] = host
	options["username"] = username
	options["password"] = password

	SyncMap.SetValue(&e.clients, host, "options", options)
}

func (e *clientManager) UnRegister(host string) {
	host = strings.ToLower(host)
	SyncMap.DelValue(&e.clients, host)
}

func (e *clientManager) GetClient(host string) (*http.Client, error) {
	// 尝试取出client
	client, err := SyncMap.GetValue(&e.clients, host, "client")
	if err != nil {
		return nil, err
	}

	// 该client存在，就返回该client
	if client != nil {
		client.(*http.Client).Timeout = 60 * time.Second
		return client.(*http.Client), nil
	}

	// 重置一个Client
	return e.ResetClient(host)
}

func (e *clientManager) ResetClient(host string) (*http.Client, error) {
	// 不存在，就取出账号密码，生成一个新的client
	options, err := SyncMap.GetValue(&e.clients, host, "options")
	if err != nil {
		return nil, err
	}

	client := &http.Client{
		Transport: &digest.Transport{
			Username: options.(map[string]interface{})["username"].(string),
			Password: options.(map[string]interface{})["password"].(string),
		},
	}
	SyncMap.SetValue(&e.clients, host, "client", client)

	client.Timeout = 60 * time.Second
	return client, nil
}
